package controllers

import (
	"fmt"
	"time"

	"github.com/beego/beego/v2/client/orm"
	beego "github.com/beego/beego/v2/server/web"
)

type UserController struct {
	beego.Controller
}

func (c *UserController) Get() {
	username := c.GetSession("username")
	if username == nil {
		c.Redirect("/", 302)
	}
	c.TplName = "user.tpl"
}

func (c *UserController) Post() {
	username := c.GetSession("username")
	if username == nil {
		c.Redirect("/", 302)
	}
	isImg := c.GetString("isImg")
	if isImg == "0" {
		phone := c.GetString("phone")
		location := c.GetString("location")
		nickname := c.GetString("nickname")
		o := orm.NewOrm()
		res, err := o.Raw("UPDATE user SET phone=?, location=?,nickname=? where username=?;", phone, location, nickname, username).Exec()
		fmt.Println(res.RowsAffected())
		fmt.Println(err)
	}
	if isImg == "1" {
		f, h, err := c.GetFile("userAvatar")
		imgUrl := "static/userAvatar/" + fmt.Sprint(time.Now().Unix()) + h.Filename
		c.SaveToFile("userAvatar", imgUrl)
		o := orm.NewOrm()
		res, err := o.Raw("UPDATE user SET avatar=? where username=?;", imgUrl, username).Exec()
		fmt.Println(res.RowsAffected())
		fmt.Println(err)
		defer f.Close()
	}

	c.Redirect("/user", 302)
}
